package com.sun.lotter.luck;

import java.util.ArrayList;
import java.util.Random;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.view.LayoutInflater;
import android.view.View;
import com.sun.base.BasePlayType;
import com.sun.bata.LotterData;
import com.sun.bata.MakeLotterNumber;
import com.sun.lotter.LotterNumberDialog;
import com.sun.lotter.R;
import com.tools.MyLog;

public class LuckPlayPage5 extends BasePlayType {
	private Sensor	sensor;
	SensorManager	sm;
	
	public LuckPlayPage5(LuckLotterActivity context) {
		super(context);
		LayoutInflater.from(context).inflate(R.layout.luck_layout_5, this);
		sm = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
		sensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
	}
	
	@Override
	public void onEvent(String e) {
		if (e.equals("on")) {
			onSensorStart();
		} else if (e.equals("off")) {
			onSensorStop();
		}
	}
	
	public void onSensorStart() {
		sm.registerListener(sensorListener, sensor, SensorManager.SENSOR_DELAY_GAME);
		
	}
	
	public void onSensorStop() {
		sm.unregisterListener(sensorListener);
	}
	
	@Override
	public void onWindowFocusChanged(boolean hasWindowFocus) {
		super.onWindowFocusChanged(hasWindowFocus);
		if (hasWindowFocus) {
			onSensorStart();
		} else onSensorStop();
	}
	
	@Override
	protected void onWindowVisibilityChanged(int visibility) {		
		super.onWindowVisibilityChanged(visibility);
		if (visibility == View.VISIBLE) {
			onSensorStart();
		} else onSensorStop();
	}
	
	SensorEventListener	sensorListener	= new SensorEventListener() {
											
											@Override
											public void onSensorChanged(SensorEvent event) {
												synchronized (this) {
													MyLog.i(Math.abs(event.values[0]) + "，" + Math.abs(event.values[1]) + "，" + Math.abs(event.values[2]));
													if (Math.abs(event.values[0]) > 11 || Math.abs(event.values[1]) > 11 || Math.abs(event.values[2]) > 11) {
														onSensorStop();
														MakeLotterNumber makeLotterNumber = new MakeLotterNumber();
														
														ArrayList<String> list = makeLotterNumber.makeLotterNumbers(new Random(), LotterData.DOUBLECOLORBALL, 0, 1);
														LotterNumberDialog dialog = new LotterNumberDialog(getContext(), list, LotterData.DOUBLECOLORBALL, 0);
														dialog.playType = LuckPlayPage5.this;
														dialog.show();
													}
												}
											}
											
											@Override
											public void onAccuracyChanged(Sensor sensor, int accuracy) {
												MyLog.d("onAccuracyChanged");
												
											}
										};
}
